package db;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.rms.*;

/**
 *
 * @author Shayan
 */
public class DatabaseHelper {

    public static int findRecordId(RecordStore rs, final String id) throws RecordStoreNotOpenException, InvalidRecordIDException {
        RecordEnumeration re = rs.enumerateRecords(new RecordFilter() {

            public boolean matches(byte[] candidate) {
                // HACK: faster than ByteArrayInputStream, DataInputStream
                String candidateId = new String(candidate, 2, 36);
                return candidateId.equalsIgnoreCase(id);
            }
        }, null, false);
        if (re.hasNextElement()) {
            return re.nextRecordId();
        }
        return -1;
    }

    public static byte[] findRecordById(RecordStore rs, final String id)
            throws RecordStoreNotOpenException, InvalidRecordIDException, IOException, RecordStoreException {

        RecordEnumeration re = rs.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            byte[] data = re.nextRecord();

            ByteArrayInputStream bin = new ByteArrayInputStream(data);
            DataInputStream in = new DataInputStream(bin);

            if (id.equalsIgnoreCase(in.readUTF())) {
                return data;
            }
        }
        return null;
    }

    // assumes name is always second field
    public static byte[] findRecordByName(RecordStore rs, final String name)
            throws RecordStoreNotOpenException, InvalidRecordIDException, IOException, RecordStoreException {

        RecordEnumeration re = rs.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            byte[] data = re.nextRecord();

            ByteArrayInputStream bin = new ByteArrayInputStream(data);
            DataInputStream in = new DataInputStream(bin);

            in.readUTF(); // id, ignore it.
            if (name.equals(in.readUTF())) {
                return data;
            }
        }
        return null;
    }
}
